package com.szh.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.szh.common.dto.es.SkuEsModel;
import com.szh.common.utils.R;
import com.szh.gulimall.search.config.ElasticSearchConfig;
import com.szh.gulimall.search.constant.ElasticSearchConstant;
import com.szh.gulimall.search.feign.ProductFeignService;
import com.szh.gulimall.search.service.SearchDetailService;
import com.szh.gulimall.search.vo.AttrResponseVo;
import com.szh.gulimall.search.vo.BrandResponseVo;
import com.szh.gulimall.search.vo.SearchParam;
import com.szh.gulimall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author: SongZiHao
 * @date: 2022/12/25
 */
@Service
public class SearchDetailServiceImpl implements SearchDetailService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SearchDetailServiceImpl.class);

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ProductFeignService productFeignService;

    /**
     * 根据参数param，动态构建出ES的检索DSL语句，从ES中检索出指定的商品详情信息
     */
    @Override
    public SearchResult search(SearchParam param) {
        SearchResult result = null;
        //1.创建检索请求对象
        SearchRequest searchRequest = buildSearchRequest(param);
        try {
            //2.执行检索请求
            SearchResponse searchResponse = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
            //3.分析响应数据，封装成我们需要的格式
            result = buildSearchResult(searchResponse, param);
        } catch (IOException ex) {
            LOGGER.error("异常信息：{}", ex.getMessage());
        }
        return result;
    }

    /**
     * 创建检索请求对象
     * 包括：模糊匹配，过滤（按照属性、分类、品牌、价格区间、库存），排序，分页，高亮，聚合
     * catalog3Id=225 & keyword=小米 & sort=saleCount_asc & hasStock=1 &
     * skuPrice=_6000 & brandId=1 & brandId=2 & attrs=1_5寸:6寸 & attrs=2_系统:安卓
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        //1.构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //1.1 模糊匹配，过滤（按照属性、分类、品牌、价格区间、库存）
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1.1 must模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        //1.1.2 filter过滤
        //filter过滤 - 分类
        if (Objects.nonNull(param.getCatalog3Id())) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        //filter过滤 - 品牌
        if (!CollectionUtils.isEmpty(param.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        //filter过滤 - 库存
        if (Objects.nonNull(param.getHasStock())) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        //filter过滤 - 价格区间
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] splitArray = param.getSkuPrice().split("_");
            if (splitArray.length == 2) {
                rangeQuery.gt(splitArray[0]).lte(splitArray[1]);
            } else if (splitArray.length == 1) {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(splitArray[0]);
                }
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(splitArray[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        //filter过滤 - 属性
        if (!CollectionUtils.isEmpty(param.getAttrs())) {
            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] split = attrStr.split("_");
                String attrId = split[0]; //检索的属性id
                String[] attrValues = split[1].split(":"); //该属性对应的属性值
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                //每一个nestedBoolQuery都必须构建生成一个nested查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        sourceBuilder.query(boolQuery);
        //1.2 排序，分页，高亮
        //1.2.1 排序
        if (!StringUtils.isEmpty(param.getSort())) {
            String[] split = param.getSort().split("_");
            SortOrder sortOrder = split[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(split[0], sortOrder);
        }
        //1.2.2 分页
        sourceBuilder.from((param.getPageNum() - 1) * ElasticSearchConstant.PRODUCT_PAGE_SIZE);
        sourceBuilder.size(ElasticSearchConstant.PRODUCT_PAGE_SIZE);
        //1.2.3 高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }
        //1.3 聚合
        //1.3.1 品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId").size(50);
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brandAgg);
        //1.3.2 分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg");
        catalogAgg.field("catalogId").size(20);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalogAgg);
        //1.3.3 属性聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(20));
        attrAgg.subAggregation(attrIdAgg);
        sourceBuilder.aggregation(attrAgg);
        LOGGER.info("构建的DSL检索语句：{}", sourceBuilder.toString());
        //2.构建检索请求对象
        SearchRequest searchRequest = new SearchRequest(
                new String[]{ElasticSearchConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }

    /**
     * 分析响应数据，封装成我们需要的格式
     */
    private SearchResult buildSearchResult(SearchResponse searchResponse, SearchParam param) {
        SearchResult result = new SearchResult();
        //1.返回所有查询到的商品信息
        List<SkuEsModel> skuEsModelList = new ArrayList<>();
        SearchHits hits = searchResponse.getHits();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                //当检索条件中有keyword时，才会添加高亮显示
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    //将检索到的商品信息中的skuTitle替换为高亮显示
                    HighlightField highlightField = hit.getHighlightFields().get("skuTitle");
                    String skuTitle = highlightField.getFragments()[0].string();
                    skuEsModel.setSkuTitle(skuTitle);
                }
                //将检索到的每一个商品加入skuEsModelList
                skuEsModelList.add(skuEsModel);
            }
        }
        result.setProducts(skuEsModelList);
        //2.返回所有商品涉及到的所有属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrAgg = searchResponse.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> attrVoBuckets = attrIdAgg.getBuckets();
        for (Terms.Bucket bucket : attrVoBuckets) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //属性id
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);
            //属性名称
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            //属性的所有值
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValueList = attrValueAgg.getBuckets().stream().map(item -> {
                String attrValue = item.getKeyAsString();
                return attrValue;
            }).collect(Collectors.toList());
            attrVo.setAttrValue(attrValueList);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);
        //3.返回所有商品涉及到的所有品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brandAgg = searchResponse.getAggregations().get("brand_agg");
        List<? extends Terms.Bucket> brandVoBuckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : brandVoBuckets) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //品牌id
            long brandId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);
            //品牌名称
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            //品牌图片
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);
        //4.返回所有商品涉及到的所有分类信息
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalogAgg = searchResponse.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> catalogVoBuckets = catalogAgg.getBuckets();
        for (Terms.Bucket bucket : catalogVoBuckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //分类id
            String catalogId = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(catalogId));
            //分类名称
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
        //5.1 返回所有分页信息 - 当前页码
        result.setPageNum(param.getPageNum());
        //5.2 返回所有分页信息 - 总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //5.3 返回所有分页信息 - 总页码
        int pageSize = ElasticSearchConstant.PRODUCT_PAGE_SIZE;
        int totalInt = (int) total;
        int totalPages = totalInt % pageSize == 0 ? totalInt / pageSize : (totalInt / pageSize + 1);
        result.setTotalPages(totalPages);
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        //6.构建面包屑导航数据
        if (!CollectionUtils.isEmpty(param.getAttrs())) {
            List<SearchResult.NavVo> navs = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                //attrs=2_系统:安卓
                //split[0]=2 属性id   split[1]=系统:安卓 属性具体值
                String[] split = attr.split("_");
                navVo.setNavValue(split[1]);
                result.getAttrIds().add(Long.parseLong(split[0]));
                //远程调用商品服务，根据属性id查询属性详情信息
                R res = productFeignService.attrInfo(Long.parseLong(split[0]));
                if (res.getCode() == 0) { //远程调用成功，设置属性名称
                    AttrResponseVo attrResponseVo = res.getData("attr", new TypeReference<AttrResponseVo>() {});
                    navVo.setNavName(attrResponseVo.getAttrName());
                } else { //远程调用失败，直接将属性名称设置为属性id
                    navVo.setNavName(split[0]);
                }
                //取消这个面包屑导航属性之后，要新跳转到的链接地址
                //先拿到当前url中所有的查询条件，去掉当前的导航属性即可（注意编码问题）
                String newLink = replaceQueryString(param, "attrs", attr);
                navVo.setLink("http://search.gulimall.com/list.html?" + newLink);
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navs);
        }
        //将品牌加入面包屑导航中
        if (!CollectionUtils.isEmpty(param.getBrandId())) {
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");
            //远程调用商品服务，根据品牌id查询品牌信息
            R res = productFeignService.listByBrandIds(param.getBrandId());
            if (res.getCode() == 0) {
                List<BrandResponseVo> brandList = res.getData("brandList", new TypeReference<List<BrandResponseVo>>() {});
                StringBuilder sb = new StringBuilder();
                String newLink = "";
                for (BrandResponseVo brand : brandList) {
                    sb.append(brand.getName()).append(";");
                    newLink = replaceQueryString(param, "brandId", String.valueOf(brand.getBrandId()));
                }
                navVo.setNavValue(sb.toString());
                navVo.setLink("http://search.gulimall.com/list.html?" + newLink);
            }
            navs.add(navVo);
            result.setNavs(navs);
        }
        //将分类加入面包屑导航中
//        if (Objects.nonNull(param.getCatalog3Id())) {
//
//        }
        LOGGER.info("从ES中按条件检索出的数据内容：{}", JSON.toJSONString(result));
        return result;
    }

    private String replaceQueryString(SearchParam param, String key, String value) {
        String newAttr = null;
        try {
            newAttr = URLEncoder.encode(value, "UTF-8");
            newAttr = newAttr.replace("+", "%20");
        } catch (UnsupportedEncodingException ex) {
            LOGGER.error("异常信息：{}", ex.getMessage());
        }
        String newLink = param.getQueryString().replace("&" + key + "=" + newAttr, "");
        return newLink;
    }
}
